//
//  LSGraffitiViewController.m
//  CROSBY
//
//  Created by Harvey on 2018/3/31.
//  Copyright © 2018年 Haley. All rights reserved.
//

#import "LSGraffitiViewController.h"
#import "LSGraffitiView.h"

@interface LSGraffitiViewController ()<UIScrollViewDelegate,LSGraffitiViewDelegate>

@property (strong, nonatomic) UIScrollView            *scrollView;
@property (strong, nonatomic) LSGraffitiView    *graffitiView;

@property (strong, nonatomic) UIView            *bottomView;

@property (strong, nonatomic) UIButton            *paintingBtn;
@property (strong, nonatomic) UIButton            *resetBtn;
@property (strong, nonatomic) UIButton            *eraserBtn;
@property (strong, nonatomic) UIButton            *dragBtn;
@property (strong, nonatomic) UIButton            *zoomoutBtn;
@property (strong, nonatomic) UILabel            *zoomLabel;
@property (strong, nonatomic) UIButton            *zoominBtn;

@property (assign, nonatomic)   BOOL         isPainting;

@property (assign, nonatomic)   BOOL         isFirst;

@end

@implementation LSGraffitiViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = showText(@"涂鸦");
    
    [self initNavigationBar];
    
    [self initSubViews];
    
    [self paintingClick:nil];
    
    self.isFirst = YES;
    
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientationDidChange) name:UIDeviceOrientationDidChangeNotification object:nil];
}

- (void)initNavigationBar
{
    UIButton *leftBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 30)];
    [leftBtn setTitle:showText(@"取消") forState:UIControlStateNormal];
    [leftBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(leftClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    
    UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 30)];
    [rightBtn setTitle:showText(@"保存") forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(rightClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
}

- (void)initSubViews
{
    UIScrollView *scroolView = [[UIScrollView alloc] initWithFrame:CGRectZero];
    scroolView.minimumZoomScale = 1;
    scroolView.maximumZoomScale = 3;
    scroolView.showsVerticalScrollIndicator = NO;
    scroolView.showsHorizontalScrollIndicator = NO;
    [self.view addSubview:scroolView];
    scroolView.delegate = self;
    self.scrollView = scroolView;
    
//    CGFloat graH = (kWidth - 20 )/kGraffiCols * kGraffiRows;
    self.graffitiView = [[LSGraffitiView alloc] initWithFrame:CGRectZero];
    self.graffitiView.delegate = self;
    [self.scrollView addSubview:self.graffitiView];
    
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectZero];
    bottomView.backgroundColor = RGBColor(25, 53, 106, 1);
    [self.view addSubview:bottomView];
    self.bottomView = bottomView;
    
    UIButton *paintingBtn = [[UIButton alloc] initWithFrame:CGRectZero];
    [paintingBtn setBackgroundImage:[UIImage imageNamed:@"ico_painting_un"] forState:UIControlStateNormal];
    [paintingBtn setBackgroundImage:[UIImage imageNamed:@"ico_painting_ing"] forState:UIControlStateSelected];
    [paintingBtn addTarget:self action:@selector(paintingClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:paintingBtn];
    self.paintingBtn = paintingBtn;
    
    UIButton *resetBtn = [[UIButton alloc] initWithFrame:CGRectZero];
    [resetBtn setBackgroundImage:[UIImage imageNamed:@"ico_un_reset"] forState:UIControlStateNormal];
    [resetBtn setBackgroundImage:[UIImage imageNamed:@"ico_reset"] forState:UIControlStateSelected];
    [resetBtn addTarget:self action:@selector(resetClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:resetBtn];
    self.resetBtn = resetBtn;
    
    UIButton *eraserBtn = [[UIButton alloc] initWithFrame:CGRectZero];
    [eraserBtn setBackgroundImage:[UIImage imageNamed:@"ic_eraser_unselected"] forState:UIControlStateNormal];
    [eraserBtn setBackgroundImage:[UIImage imageNamed:@"ic_eraser_selected"] forState:UIControlStateSelected];
    [eraserBtn addTarget:self action:@selector(eraserClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:eraserBtn];
    self.eraserBtn = eraserBtn;
    
    UIButton *dragBtn = [[UIButton alloc] initWithFrame:CGRectZero];
    [dragBtn setBackgroundImage:[UIImage imageNamed:@"ico_undragging"] forState:UIControlStateNormal];
    [dragBtn setBackgroundImage:[UIImage imageNamed:@"ico_dragging"] forState:UIControlStateSelected];
    [dragBtn addTarget:self action:@selector(dragClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:dragBtn];
    self.dragBtn = dragBtn;
    
    UIButton *zoomoutBtn = [[UIButton alloc] initWithFrame:CGRectZero];
    [zoomoutBtn setBackgroundImage:[UIImage imageNamed:@"ic_zoomout"] forState:UIControlStateNormal];
    [zoomoutBtn addTarget:self action:@selector(zoomoutClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:zoomoutBtn];
    self.zoomoutBtn = zoomoutBtn;
    
    UILabel *zoomlabel = [[UILabel alloc] initWithFrame:CGRectZero];
    zoomlabel.textColor = [UIColor lightGrayColor];
    zoomlabel.textAlignment = NSTextAlignmentCenter;
    zoomlabel.text = @"100%";
    [self.bottomView addSubview:zoomlabel];
    self.zoomLabel = zoomlabel;
    
    UIButton *zoominBtn = [[UIButton alloc] initWithFrame:CGRectZero];
    [zoominBtn setBackgroundImage:[UIImage imageNamed:@"ic_zoomin"] forState:UIControlStateNormal];
    [zoominBtn addTarget:self action:@selector(zoominClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:zoominBtn];
    self.zoominBtn = zoominBtn;
}

#pragma mark - notification method
- (void)deviceOrientationDidChange
{
    if (self.isFirst) {
        UIEdgeInsets safeAreaInsets = UIEdgeInsetsZero;
        if (@available(iOS 11.0, *)) {
            safeAreaInsets = [UIApplication sharedApplication].keyWindow.safeAreaInsets;
        }
        NSLog(@"deviceOrientationDidChange:%ld",(long)[UIDevice currentDevice].orientation);
        
        CGFloat topTotalH = [self topTotalHeight];
        CGFloat maxWidth = kWidth - safeAreaInsets.left - safeAreaInsets.right;
        CGFloat maxHeight = kHeight - topTotalH - 44 - safeAreaInsets.bottom;
        
        CGFloat squareH = maxHeight / kGraffiRows;
        CGFloat squareW = maxWidth / kGraffiCols;
        CGFloat squareWidth = MIN(squareH, squareW);
        CGFloat graffViewWidth = squareWidth * kGraffiCols;
        CGFloat graffViewHeight = squareWidth * kGraffiRows;
        self.graffitiView.frame = CGRectMake(0, 0, graffViewWidth, graffViewHeight);
        
        CGFloat scrollX = (maxWidth - graffViewWidth) * 0.5 + safeAreaInsets.left;
        CGFloat scrollY = (maxHeight - graffViewHeight) * 0.5;
        self.scrollView.frame = CGRectMake(scrollX, scrollY, graffViewWidth, graffViewHeight);
        self.scrollView.contentSize = CGSizeMake(graffViewWidth, graffViewHeight);
        
        CGFloat bottomY = kHeight - topTotalH - 44 - safeAreaInsets.bottom;
        
        self.bottomView.frame = CGRectMake(0, bottomY, kWidth, 44);
        
        CGFloat btnW = 24;
        self.paintingBtn.frame = CGRectMake(20, 10, btnW, btnW);
        
        self.resetBtn.frame = CGRectMake(20 + 64, 10, btnW, btnW);
        
        self.eraserBtn.frame = CGRectMake(20 + 128, 10, btnW, btnW);
        
        self.dragBtn.frame = CGRectMake(20 + 192, 10, btnW, btnW);
        
        self.zoomoutBtn.frame = CGRectMake(20 + 256, 10, btnW, btnW);
        
        self.zoomLabel.frame = CGRectMake(20 + 285, 10, 50, btnW);
        
        self.zoominBtn.frame = CGRectMake(20 + 340, 10, btnW, btnW);
        
        self.isFirst = NO;
    }
}

#pragma mark - override method
- (void)initBgView
{
    self.view.backgroundColor = RGBColor(31, 30, 69, 1);
}

// 如果需要横屏的时候，一定要重写这个方法并返回NO
- (BOOL)prefersStatusBarHidden
{
    return NO;
}

//进入界面时强制横屏
- (void)viewWillAppear:(BOOL)animated
{
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int val = UIInterfaceOrientationLandscapeRight;
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
    
}

//退出界面时强制竖屏
- (void)viewWillDisappear:(BOOL)animated
{
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        int val = UIDeviceOrientationPortrait;
        [invocation setArgument:&val atIndex:2];
        [invocation invoke];
    }
}

#pragma mark - private tool method
- (CGFloat)topTotalHeight
{
    CGFloat height = 34 + 20;
    if (kIPhoneX) {
        height = 34;
        return height;
    }
    
    if (kIsPlus) {
        height = 44 + 20;
        return height;
    }
    
    return height;
}

#pragma mark - click events
- (void)leftClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)rightClick
{
    NSLog(@"保存");
    if (!self.graffitiView.data || self.graffitiView.data.count == 0) {
        return;
    }
    
    BOOL isSelected = NO;
    for (int i = 0; i < self.graffitiView.data.count; i++) {
        NSArray *tols = [self.graffitiView.data objectAtIndex:i];
        for (int j = 0; j < tols.count; j++) {
            NSNumber *number = [tols objectAtIndex:j];
            if ([number boolValue]) {
                isSelected = YES;
                break;
            }
        }
    }
    
    if (!isSelected) {
        return;
    }
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSMutableArray *graffDataList = [NSMutableArray arrayWithArray:[userDefaults objectForKey:kGraffDataListKey]];
    [graffDataList addObject:self.graffitiView.data];
    [userDefaults setObject:graffDataList forKey:kGraffDataListKey];
    [userDefaults synchronize];
    
    if (_graffCompletion) {
        _graffCompletion();
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)paintingClick:(UIButton *)btn
{
    self.paintingBtn.selected = YES;
    self.resetBtn.selected = NO;
    self.eraserBtn.selected = NO;
    self.dragBtn.selected = NO;
    
    self.isPainting = YES;
    self.scrollView.scrollEnabled = NO;
}

- (void)resetClick:(UIButton *)btn
{
    self.paintingBtn.selected = NO;
    self.resetBtn.selected = NO;
    self.eraserBtn.selected = NO;
    self.dragBtn.selected = NO;
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:showText(@"清空当前涂鸦") preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:showText(@"取消") style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:showText(@"确定") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"确定");
        [self.graffitiView reset];
        [self paintingClick:nil];
    }];
    [alertVC addAction:cancelAction];
    [alertVC addAction:sureAction];
    
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)eraserClick:(UIButton *)btn
{
    self.paintingBtn.selected = NO;
    self.resetBtn.selected = NO;
    self.eraserBtn.selected = YES;
    self.dragBtn.selected = NO;
    
    self.isPainting = NO;
    self.scrollView.scrollEnabled = NO;
}

- (void)dragClick:(UIButton *)btn
{
    self.paintingBtn.selected = NO;
    self.resetBtn.selected = NO;
    self.eraserBtn.selected = NO;
    self.dragBtn.selected = YES;
    
    self.isPainting = YES;
    
    self.scrollView.scrollEnabled = YES;
}

// 缩小按钮点击事件
- (void)zoomoutClick:(UIButton *)btn
{
    self.scrollView.zoomScale -= 0.25;
    CGFloat currentScale = self.scrollView.zoomScale;
    int currentValue = (int)(currentScale * 100);
    
    self.zoomLabel.text = [NSString stringWithFormat:@"%d%%",currentValue];
    CGFloat graffH = self.graffitiView.frame.size.height;
    CGFloat graffW = self.graffitiView.frame.size.width;
    
    UIEdgeInsets safeAreaInsets = UIEdgeInsetsZero;
    if (@available(iOS 11.0, *)) {
        safeAreaInsets = [UIApplication sharedApplication].keyWindow.safeAreaInsets;
    }
    CGFloat topTotalH = [self topTotalHeight];
    CGFloat maxWidth = kWidth - safeAreaInsets.left - safeAreaInsets.right;
    CGFloat maxHeight = kHeight - topTotalH - 44 - safeAreaInsets.bottom;
    
    CGFloat scrollX = (maxWidth - graffW) * 0.5 + safeAreaInsets.left;
    CGFloat scrollY = (maxHeight - graffH) * 0.5;
    CGFloat scrollW = graffW;
    CGFloat scrollH = graffH;
    if (graffH > maxHeight) {
        scrollY = 0;
        scrollH = maxHeight;
    }
    if (graffW > maxWidth) {
        scrollX = safeAreaInsets.left;
        scrollW = maxWidth;
    }
    
    self.scrollView.frame = CGRectMake(scrollX, scrollY, scrollW, scrollH);
}

// 放大按钮点击事件
- (void)zoominClick:(UIButton *)btn
{
    self.scrollView.zoomScale += 0.25;
    CGFloat currentScale = self.scrollView.zoomScale;
    int currentValue = (int)(currentScale * 100);
    
    self.zoomLabel.text = [NSString stringWithFormat:@"%d%%",currentValue];
    CGFloat graffH = self.graffitiView.frame.size.height;
    CGFloat graffW = self.graffitiView.frame.size.width;
    
    UIEdgeInsets safeAreaInsets = UIEdgeInsetsZero;
    if (@available(iOS 11.0, *)) {
        safeAreaInsets = [UIApplication sharedApplication].keyWindow.safeAreaInsets;
    }
    CGFloat topTotalH = [self topTotalHeight];
    CGFloat maxWidth = kWidth - safeAreaInsets.left - safeAreaInsets.right;
    CGFloat maxHeight = kHeight - topTotalH - 44 - safeAreaInsets.bottom;
    
    CGFloat scrollX = (maxWidth - graffW) * 0.5 + safeAreaInsets.left;
    CGFloat scrollY = (maxHeight - graffH) * 0.5;
    CGFloat scrollW = graffW;
    CGFloat scrollH = graffH;
    if (graffH > maxHeight) {
        scrollY = 0;
        scrollH = maxHeight;
    }
    if (graffW > maxWidth) {
        scrollX = safeAreaInsets.left;
        scrollW = maxWidth;
    }
    
    self.scrollView.frame = CGRectMake(scrollX, scrollY, scrollW, scrollH);
}

#pragma mark - LSGraffitiViewDelegate
- (void)graffitiView:(LSGraffitiView *)graffitiView touchOn:(LSSquareView *)view
{
    NSIndexPath *indexPath = view.indexPath;
    NSNumber *number = graffitiView.data[indexPath.section][indexPath.row];
    number = @(self.isPainting);
    
    graffitiView.data[indexPath.section][indexPath.row] = number;
    view.isSelected = self.isPainting;
}

#pragma mark - UIScrollViewDelegate
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return self.graffitiView;
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidZoom:(UIScrollView *)scrollView
{
    CGFloat currentScale = self.scrollView.zoomScale;
    int currentValue = (int)(currentScale * 100);
    
    self.zoomLabel.text = [NSString stringWithFormat:@"%d%%",currentValue];
    CGFloat graffH = self.graffitiView.frame.size.height;
    CGFloat graffW = self.graffitiView.frame.size.width;
    
    UIEdgeInsets safeAreaInsets = UIEdgeInsetsZero;
    if (@available(iOS 11.0, *)) {
        safeAreaInsets = [UIApplication sharedApplication].keyWindow.safeAreaInsets;
    }
    CGFloat topTotalH = [self topTotalHeight];
    CGFloat maxWidth = kWidth - safeAreaInsets.left - safeAreaInsets.right;
    CGFloat maxHeight = kHeight - topTotalH - 44 - safeAreaInsets.bottom;
    
    CGFloat scrollX = (maxWidth - graffW) * 0.5 + safeAreaInsets.left;
    CGFloat scrollY = (maxHeight - graffH) * 0.5;
    CGFloat scrollW = graffW;
    CGFloat scrollH = graffH;
    if (graffH > maxHeight) {
        scrollY = 0;
        scrollH = maxHeight;
    }
    if (graffW > maxWidth) {
        scrollX = safeAreaInsets.left;
        scrollW = maxWidth;
    }
    
    self.scrollView.frame = CGRectMake(scrollX, scrollY, scrollW, scrollH);
}

@end
